import { Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { Role } from './entities/role.entity';
import { User } from '../users/entities/user.entity';
import { Permission } from '../permission/entities/permission.entity';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role) private readonly role: Repository<Role>,
    @InjectRepository(User) private readonly user: Repository<User>,
    @InjectRepository(Permission)
    private readonly permission: Repository<Permission>,
  ) {}

  async create(createRoleDto: CreateRoleDto) {
    const role = await this.role.findOne({
      where: {
        roleName: createRoleDto.roleName,
      },
      relations: ['permissions'],
    });
    if (role) {
      return {
        msg: `角色 ${createRoleDto.roleName}已存在,无法创建`,
      };
    }

    // todo：创建时没有添加权限信息
    const newRole = this.role.create(createRoleDto);
    await this.role.save(newRole);

    return {
      msg: `角色${createRoleDto.roleName}创建成功`,
    };
  }

  async findAll() {
    const roleList = await this.role.find({
      relations: ['permissions'],
    });
    return {
      data: {
        roleList,
        total: await this.role.count(),
      },
    };
  }

  async findOne(id: string) {
    const role = await this.role.findOne({
      where: { id },
      relations: ['users', 'permissions'],
    });
    if (!role) {
      return `Role with ID "${id}" not found`;
    }
    return role;
  }

  async update(id: string, updateRoleDto: UpdateRoleDto) {
    const role = await this.role.findOne({
      where: { id },
      relations: ['permissions'],
    });
    if (!role)
      return {
        msg: '没有此角色信息',
      };

    // 更新角色信息
    if (updateRoleDto.roleName) {
      role.roleName = updateRoleDto.roleName;
    }
    if (updateRoleDto.roleCode) {
      role.roleCode = updateRoleDto.roleCode;
    }

    if (updateRoleDto.roleLevel) {
      role.roleLevel = updateRoleDto.roleLevel;
    }

    // 更新权限信息
    if (updateRoleDto.permissions) {
      role.permissions = await this.permission.find({
        where: {
          id: In(updateRoleDto.permissions),
        },
      });
    }

    await this.role.save(role);
    // 保存更新后的角色
    return {
      msg: '更新角色信息成功',
    };
  }

  async remove(id: string) {
    const role = await this.role.findOne({
      where: { id },
    }); // 可以使用上面定义的findOne方法
    await this.role.remove(role);
  }
}
